<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Pools;

use App\Models\ReservePool;
use App\Service\BaseService;

class ReserveService extends BaseService
{
    /**
     * @param $amount
     */
    public function injectFunds($amount)
    {
        if ($amount < 0) {
            return;
        }
        $rp = $this->getReservePool();
        $rp->source_from_initial += $amount;
        $rp->total_amount = $rp->source_from_exceeded + $rp->source_from_initial;
        $rp->save();
    }

    /**
     * 超额释放.
     * @param $amount
     */
    public function excessRelease($amount)
    {
        if ($amount < 0) {
            return;
        }
        $rp = $this->getReservePool();
        $rp->source_from_exceeded += $amount;
        $rp->total_amount = $rp->source_from_exceeded + $rp->source_from_initial;
        $rp->save();
    }

    /**
     * 超额释放 千分之1.
     */
    public function excessReleaseRatio(): float
    {
        return 0.001;
    }

    /**
     * 初始化储备金池.
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|void
     */
    protected function initReserve()
    {
        $rp = ReservePool::query()->where([
            'date' => now()->subDay()->toDateString(),
        ])->first();
        if (empty($rp)) {
            $data = [
                'date' => now()->toDateString(),
            ];
        } else {
            $data = $rp->toArray();
            unset($data['id']);
            $data['date'] = now()->toDateString();
        }
        return ReservePool::query()->create($data);
    }

    protected function getReservePool()
    {
        $model = ReservePool::query()->latest('date')->first();
        if (empty($model)) {
            $model = $this->initReserve();
        }
        if ($model->date != now()->toDateString()) {
            $model = $this->initReserve();
        }
        return $model;
    }
}
